<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>用户</title>
</head>
<link rel="stylesheet" href="./css/index.css">
<body>
  <div class="box1">
      <h1>添加用户</h1>
      姓名: <input type="text" id="username"> <br>
      性别: <input type="text" id="gender"> <br>
      年龄: <input type="text" id="age"> <br>
      <button id="btn">添加用户</button>
  </div>

  <div class="box2" >
    <h1>用户列表</h1><a href="javaScript:;" class="add">添加用户</a>
    <table border="1">
      <thead>
        <th>序号</th>
        <th>姓名</th>
        <th>性别</th>
        <th>年龄</th>
        <th>操作</th>
      </thead>
      <tbody>

      </tbody>
    </table>
  </div>
  
  </table>
</body>
<script src="./js/tool.js"></script>
<script>

//获取所有的用户信息
ajax('/user/list').then(res=>{
  document.querySelector('tbody').innerHTML=mkli(res)
})

//点击添加用户按钮
document.querySelector('#btn').onclick=function(){
  let username =document.querySelector('#username').value;
  let age =document.querySelector('#age').value;
  let gender =document.querySelector('#gender').value;

  if(!username ||!age || !gender){ //判定不能为空
    alert('请输入内容')
    return false;
  }

  var reg=/^(男|女)$/ //性别限定男或者女
  if(!reg.test(gender)){ 
    alert('性别请输入男或者女')
    return false;
  }

  var reg1 =/^(([0-9]|[1-9][1-9]|1[0-7][0-9])(\\.[0-9]+)?|180)$/ //限定年龄
  if(!reg1.test(age)){
    alert('请输入正常年龄')
    return false
  }
  //ajax请求
  ajax('/user/add',`name=${username}&age=${age}&gender=${gender}`,'post').then(res=>document.querySelector('tbody').innerHTML=mkli(res))
  document.querySelector('#username').value=document.querySelector('#age').value=document.querySelector('#gender').value='';
  document.querySelector('.box1').style.display='none'
  document.querySelector('.box2').style.display='block'
  return false
}

//点击用户列表添加用户
document.querySelector('.add').onclick=function(){
  document.querySelector('.box1').style.display='block'
  document.querySelector('.box2').style.display='none'
}

//删除
function del(id){
  if(confirm('确定删除吗')){
    ajax(`/user/${id}`,'','delete').then(res=>document.querySelector('tbody').innerHTML=mkli(res))
  } 
}

</script>
</html>